import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, TextInput,
  PixelRatio, Platform, ScrollView, Modal, FlatList, Alert
} from 'react-native';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { productSelectStyle } from '../_common/style';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;
let optionPicSourse = require('../../../../imgs/global/option.png');
let selectedPicSourse = require('../../../../imgs/global/success.png');
let searchIcon = require('../../../../imgs/customer/searchLeft.png');
const correct = require('../../../../imgs/global/correct.png');


/*
  chang : 企业变更 特别展示  值: boolean ( true ,false)
  onlyOption ：仅看可认领  值: boolean ( true ,false)
  optionBox: 是否显示选项框  值: boolean ( true ,false)
  secondRight:二级目录右边展示类型 值: boolean ( true ,false)
  data : 商品数据  值 : JSON对象
  widthoutTop : 是否展示头部。类型 boolean：true 时不显示头部筛选及操作按钮，默认为false
  renderLeft : 自定义头部-左侧图形。默认 this._renderLeftBtns()
  renderRight : 自定义头部-右侧图形。默认 this._renderRightBtns()
  middleContent : 自定义头部-中间图形。默认 this._renderFilterContent()
  bannerContent: 自定义横幅栏。默认this._renderBannerContent()
  secondRightContent:自定义二级目录右边展示。
  leftBtnsList : 默认头部-左侧按钮。类型obj：{ btnText:'确认添加',btnFun:()=>{console.log(1)}}，不传则不展示
  rightBtnsList : 默认头部-右侧按钮。类型 obj:{ btnText:'确认添加',btnFun:()=>{console.log(1)}}，不传则不展示
  bannerBtnContent:默认中间横幅展示字段。类型 string:''，不传则不展示
  searching:一般搜索的数据没有变化的时候不会触发componentWillReceiveProps函数 status一直等于loading 需要有个变量反馈搜索完毕 值: boolean ( true ,false)
*/


export class ProductEditing extends Component {

  constructor(props) {
    super(props);
    let { data, single, onlyOption, secondRight, secondRightContent, optionBox, showLossInfo, showLogInfo, searching } = this.props;
    single = single ? (single == 'true' ? true : false) : true;
    this.state = {
      sideDataSource: data || [], // 一级数据
      mainDataSource: data && data[0] && data[0].goodsList || [], // 二级数据
      sideCheckData: [], // 一级数据回显
      mainCheckData: [],   // 二级数据回显
      status: 'loading',  // 数据加载状态
      single,
      firstIndex: 0,
      onlyOption: onlyOption || false,
      secondRight: secondRight || false,
      secondRightContent: secondRightContent || false,
      optionBox: optionBox || false,
      showLossInfo: showLossInfo || false,
      showLogInfo: showLogInfo || false,
      secondShow: true,
      searching: searching || false
    }
    this.goodsData = {}; // 参数收集
  }

  componentWillMount() {
    let { sideDataSource, firstIndex } = this.state;
    if (!sideDataSource.length) {
      return;
    }
    else {
      this.setState({
        status: 'data'
      })
    }
    this._sideCheckFn(sideDataSource[firstIndex].goodsCateCode);

  }

  componentWillReceiveProps(props) {
    let { data, onlyOption, searching, optionBox } = props || {};
    let { firstIndex } = this.state;
    let status;
    if (searching) {
      status = 'loading'
    }
    else {
      status = data && data.length ? 'data' : 'empty'
    }
    this.setState({
      sideDataSource: data || [],
      onlyOption: onlyOption,
      status: status,
      optionBox
    }, () => {
      let { sideDataSource } = this.state;
      if (!sideDataSource.length) return;
      this._sideCheckFn(sideDataSource[firstIndex > sideDataSource.length ? 0 : firstIndex].goodsCateCode);
    })
  }

  // 一级选择
  _sideCheckFn = (goodsCateCode, firstIndex) => {
    let { sideDataSource, mainDataSource, sideCheckData, onlyOption, secondShow } = this.state;
    sideDataSource && sideDataSource.map((item) => {
      if (item.goodsCateCode == goodsCateCode) {
        sideCheckData[0] = { goodsCode: item.goodsCateCode, goodsName: item.goodsCateName };
        item.selected = true;
        mainDataSource = item.goodsList;
      } else {
        item.selected = false;
      }
      return item;
    })
    if (firstIndex == undefined) {
      firstIndex = this.state.firstIndex;
    }
    if (onlyOption) {
      let showNum = 0
      mainDataSource.map((item) => {
        if (item.canClaimFlag === false) {
          showNum++
        }
      })
      if (showNum === mainDataSource.length) {
        secondShow = false
      }
      else {
        secondShow = true
      }
    }
    else {
      secondShow = true
    }
    this.setState({
      sideDataSource,
      mainDataSource,
      sideCheckData,
      firstIndex,
      secondShow,
    })
  }

  //根据数据显示第一个数据
  // _formattingData (data) {
  //   console.log(data)
  //   if (data && data.length) {
  //     data[0].selected = true;
  //     this.setState({
  //       status: 'data',
  //       sideDataSource: data
  //     }, () => {
  //       this._sideCheckFn(data[0].goodsCateCode || '');
  //     })
  //   } else {
  //     this.setState({
  //       status: 'empty',
  //       sideDataSource: data
  //     })
  //   }
  // }

  //搜索
  _searchFn = () => {
    let { searchPress } = this.props;
    this.setState({
      status: 'loading',
      mainCheckData: []
    }, async () => {
      //获取数据
      let goodsData = searchPress && await searchPress(this.goodsData);
      //根据数据初始化
      // this._formattingData(goodsData, true);
    })
  }

  // 搜索
  _writeFn = async (val) => {
    let searchCode = val
    this.goodsData.searchCode = searchCode;
    this._searchFn();
  }

  //二级数据
  _renderMain = (data) => {
    const { goodsName, select, goodsCode, canClaimFlag, staffNameList, applyStaffNameList, secondRightContent,
      applyAddFlag, operateType, limitLossDays, lastLossTime, noCheckFlag } = data.item;
    let { onlyOption, secondRight, optionBox, showLossInfo, showLogInfo } = this.state;
    let { change, getLogList } = this.props;
    return (
      <View>
        {/* <Text onPress={()=>{console.log(this.props.data)}}>show</Text> */}
        {!onlyOption || canClaimFlag ?
          <View style={styles.listMainSelect}>
            <View style={styles.listFlex}>
              {optionBox ?
                <TouchableOpacity style={[styles.lockView, { borderColor: canClaimFlag ? '#1660c8' : '#B5BAC1' }]}
                  onPress={() => canClaimFlag && this._checkSecond(data.index, select)}>
                  <View style={styles.listFlex}>
                    {!canClaimFlag && noCheckFlag !== '1' ? <Image style={[styles.lockImage, { tintColor: '#B5BAC1' }]} source={correct} /> : null}
                    {select ? <Image style={[styles.lockImage, { tintColor: canClaimFlag ? '#1660c8' : '#B5BAC1' }]} source={correct} /> : null}
                  </View>
                </TouchableOpacity>
                : null}
              <View style={{ marginTop: -3 }}>
                {canClaimFlag ?
                  <View><Text style={select ? styles.listSideTextSelected : styles.listSideText}>{goodsName}</Text></View> :
                  <View>
                    <Text style={{ fontSize: 14 * scale, color: '#7F7F7F' }}>{goodsName}</Text>
                    {change && <Text style={[styles.changeText]}>{operateType == 'D' ? '删' : operateType == 'C' ? '增' : ''}</Text>}
                  </View>
                }
                {
                  applyStaffNameList && applyStaffNameList.length ?
                    applyStaffNameList.map((item, index) => {
                      return (<View key={index} style={{ flexDirection: 'row', alignItems: 'center' }}>
                        <Text style={optionBox ? styles.applyStaffName : styles.applyStaffNameNO}>{item}</Text>
                        <Text style={styles.auditingText}>审</Text>
                      </View>)
                    }) : null
                }
                {
                  staffNameList && staffNameList.length ?
                    staffNameList.map((item, index) => {
                      return (<Text style={optionBox ? styles.applyStaffName : styles.applyStaffNameNO} key={index}>{item}</Text>)
                    }) : null
                }

              </View>
            </View>
            <View>
              {secondRight && applyAddFlag ?
                <Text style={{ fontSize: 10 * scale, color: '#7F7F7F' }}>新增审批中</Text>
                : null
              }
              {
                secondRightContent ? secondRightContent() : null
              }

              {showLossInfo ? <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                <Text style={[styles.lossDateText, { color: limitLossDays ? '#E02020' : '#D0CCCC' }]}>{limitLossDays ? `${limitLossDays}天后将流失` : (lastLossTime && lastLossTime.substring(0, 10))}</Text>
                {showLogInfo ? <Text style={styles.approveLogText} onPress={() => { getLogList && getLogList(goodsCode) }}>日志</Text> : null}
              </View> : null
              }
            </View>
          </View> : null}

      </View>
    );
  }

  //一级数据
  _renderSide = (side) => {
    let { goodsCateName, goodsCateCode, goodsList, selected, select, canClaimFlag } = side.item;
    // let curStyle = (selected) ? styles.listSideRowCur : null;
    let { onlyOption, optionBox } = this.state;
    let cateName = goodsCateName && goodsCateName.length > 5 ? `${goodsCateName.substring(0, 3)}...` : goodsCateName;
    // canClaimFlag 能否认领 optionBox 是否显示选项框 select 已选择 selected 被选中 canClaimFlag 是否能被选中
    return (
      <View>
        {canClaimFlag || !optionBox ?
          <TouchableOpacity onPress={() => { this._sideCheckFn(goodsCateCode, side.index); }} activeOpacity={0.5} style={styles.listSideRow}>
            {optionBox ? <TouchableOpacity onPress={() => this._checkFirst(side.index, select)} style={{ height: '100%', justifyContent: 'center' }}>
              <View style={styles.lockView}>
                {select ? <Image style={styles.lockImage} source={correct} /> : null}
              </View>
            </TouchableOpacity> : null}
            <Text style={selected ? styles.listSideTextSelected : styles.listSideText}>{cateName}</Text>
            {selected ? <View style={{
              width: 12 * scale, height: 12 * scale,
              backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', right: -22
            }}></View> : null}
          </TouchableOpacity> :
          <View>
            {!onlyOption ?
              <View style={styles.listSideRow}>
                {optionBox ? <View style={[styles.lockView, { borderColor: '#B5BAC1' }]} onPress={() => this._checkFirst(side.index, select)}>
                  {select ? <Image style={{ width: 8 * scale, height: 6 * scale, tintColor: '#616263' }} source={correct} /> : null}
                </View> : null}
                <Text style={{ fontSize: 14 * scale, color: '#7F7F7F' }}>{cateName}</Text>
                {selected ? <View style={{
                  width: 12 * scale, height: 12 * scale,
                  backgroundColor: '#fff', transform: [{ 'rotate': '45deg' }], position: 'absolute', right: -8
                }}></View> : null}
              </View> : null}
          </View>
        }
      </View>

    );
  }
  //头部筛选输入框
  _renderFilterContent() {
    return (
      <TouchableOpacity activeOpacity={1} onPress={() => { this.refs.searchInput.focus() }} style={styles.searchBg}>
        <Image source={searchIcon} style={styles.searchImg} />
        <TextInput
          ref={'searchInput'}
          style={styles.searcuhInput}
          underlineColorAndroid='transparent'
          placeholder={this.props.placeholderText || '请输入分类名称'}
          onChangeText={(value) => {
            this._writeFn(value);
          }}
          returnKeyType={'search'}
        />
      </TouchableOpacity>
    )
  }
  //头部左测自定义框
  _renderLeftBtns() {
    let { leftBtnsList } = this.props;
    return (
      <View style={productSelectStyle.topBtns}>
        {
          leftBtnsList ?
            <View style={productSelectStyle.topBtns}>
              <Text style={productSelectStyle.topBtnText} onPress={leftBtnsList.btnFun} >{leftBtnsList.btnText}</Text>
              <TouchableOpacity onPress={leftBtnsList.iconFun} >
                <Image source={leftBtnsList.iconImg} style={productSelectStyle.topBtnIcon} />
              </TouchableOpacity>
            </View>
            : null
        }
      </View >
    )
  }
  //头部和底部之间横幅栏自定义框
  _renderbannerContent() {
    let { bannerBtnContent } = this.props;
    return (
      <View style={styles.bannerBox}>
        {
          bannerBtnContent ?
            <Text style={styles.bannerText}>{bannerBtnContent}</Text>
            : null
        }
      </View >
    )
  }
  //头部右测自定义框
  _renderRightBtns() {
    let { rightBtnsList } = this.props;
    return (
      <View style={productSelectStyle.topBtns}>
        {
          rightBtnsList && rightBtnsList.length ?
            rightBtnsList.map((item, index) => {
              return (
                <Text key={index} style={productSelectStyle.topBtnText} onPress={() => { item.btnFun(this.state.sideDataSource) }}>{item.btnText}</Text>
              )
            }) : null
        }
      </View>
    )
  }
  //一级勾选
  _checkFirst = (index, select) => {
    let { confirmData } = this.props;
    let { sideDataSource } = this.state;
    sideDataSource[index].select = !select
    sideDataSource[index].goodsList.map(item => {
      if (item.canClaimFlag) {
        item.select = !select
      }
    })
    this.setState({
      sideDataSource,
    }, () => confirmData && confirmData(this.state.sideDataSource));
  }

  //二级勾选
  _checkSecond = (index, select) => {
    let { confirmData } = this.props;
    let { sideDataSource, mainDataSource, firstIndex } = this.state;
    let selectfirst = true
    mainDataSource[index].select = !select
    if (!mainDataSource[index].select) {
      sideDataSource[firstIndex].select = false
    }
    else {
      mainDataSource.map(item => {
        if (item.canClaimFlag) {
          if (!item.select) {
            selectfirst = false
          }
        }
      })
      sideDataSource[firstIndex].select = selectfirst
    }
    this.setState({
      mainDataSource
    }, () => confirmData && confirmData(this.state.sideDataSource));
  }

  render() {
    let { sideDataSource, mainDataSource, status, onlyOption, secondShow } = this.state;
    let { cancelPress, change, middleContent, renderLeft, renderRight, widthoutTop, bannerContent } = this.props;
    return (
      <View style={styles.containerModal}>
        {
          !widthoutTop ?
            <View style={styles.searchBox}>
              {renderLeft ? renderLeft() : this._renderLeftBtns()}
              {middleContent ? middleContent() : this._renderFilterContent()}
              {renderRight ? renderRight() : this._renderRightBtns()}
            </View> : null
        }
        {bannerContent ? bannerContent() : this._renderbannerContent()}
        <View style={styles.listView}>
          {status === 'data' ? (
            <View style={{ flexDirection: 'row' }}>
              <View style={styles.listSideWrap}>
                <FlatList
                  extraData={this.state}
                  style={styles.listSideView}
                  data={sideDataSource}
                  renderItem={this._renderSide}
                />
              </View>
              <ScrollView
                horizontal={true}
                style={styles.listMainWrap}>
                {
                  (mainDataSource && mainDataSource.length > 0 && secondShow) ? (
                    <FlatList
                      extraData={this.state}
                      style={styles.listMainView}
                      data={mainDataSource}
                      renderItem={this._renderMain}
                    />
                  ) : (
                      <View style={{ width: 255 * scale, height: '70%' }}>
                        <PageStatusIndex status={'empty'} emptyText={'该类目暂时无子商品'} />
                      </View>
                    )
                }
              </ScrollView>
            </View>
          ) : (<View style={{ flex: 1, height: '70%' }}>
            <PageStatusIndex status={status} emptyText={'暂无品类'} />
          </View>)}
        </View>
      </View>
    );
  }
}


const styles = StyleSheet.create({
  containerModal: {
    width: 375 * scale,
    backgroundColor: '#fff',
    borderRadius: 15 * scale,
    flex: 1
  },
  listHead: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    height: 52 * scale,
    width: 375 * scale,
    alignItems: 'center',
  },
  listHeadText: {
    fontSize: 16 * scale,
    color: style.color.themeColor,
    paddingTop: 5 * scale,
    paddingBottom: 5 * scale,
    paddingLeft: 8 * scale,
    paddingRight: 8 * scale
  },
  listView: {
    flex: 1,
    flexDirection: 'row',
    borderTopColor: '#F4F7FE',

  },
  listSideWrap: {
    paddingLeft: 20 * scale,
    backgroundColor: '#F4F7FE',
  },
  listSideView: {
    width: 116 * scale,
  },
  listSideRow: {
    height: 50 * scale,
    width: 100 * scale,
    alignItems: 'center',
    flexDirection: 'row',
  },
  listSideRowCur: {
    backgroundColor: '#fff',
  },
  listSideTextSelected: {
    fontSize: 14 * scale,
    color: '#000000',
    fontWeight: 'bold'
  },
  listSideText: {
    fontSize: 14 * scale,
    color: '#000000',
  },
  longText: {
    fontSize: 13 * scale,
    color: '#8B8B8B',
    width: 160 * scale
  },
  listMainWrap: {
    paddingBottom: 20 * scale,
    backgroundColor: '#fff',
    width: 255 * scale,
  },
  listMainView: {
    width: 255 * scale,
    paddingLeft: 2 * scale,
    paddingRight: 20 * scale,
    backgroundColor: '#fff'
  },
  listMainRow: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    paddingBottom: 10 * scale,
    paddingLeft: 10 * scale,
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  listMainSelect: {
    flexDirection: 'row',
    paddingTop: 10 * scale,
    paddingBottom: 10 * scale,
    paddingLeft: 10 * scale,
    justifyContent: 'space-between',
  },
  optionPic: {
    width: 14 * scale,
    height: 14 * scale,
    marginLeft: 10 * scale,
    marginRight: 10 * scale
  },
  searchBox: {
    paddingTop: 13 * scale,
    paddingBottom: 5 * scale,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchBg: {
    flex: 1,
    backgroundColor: '#F4F7FE',
    borderRadius: 4 * scale,
    paddingTop: 8 * scale,
    paddingBottom: 8 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    marginLeft: 12 * scale,
    marginRight: 12 * scale,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchBtn: {
    fontSize: 12 * scale,
    color: style.color.themeColor,
    marginLeft: 10 * scale,
    padding: 5 * scale
  },
  searchImg: {
    width: 11 * scale,
    height: 11 * scale,
  },
  searcuhInput: {
    paddingVertical: 0,
    height: 18 * scale,
    fontSize: 12 * scale,
    paddingLeft: 20 * scale,
    width: 170 * scale,
  },
  selectNumber: {
    borderRadius: 5 * scale,
    width: 20 * scale,
    height: 14 * scale,
    marginLeft: 5 * scale,
    fontSize: 11 * scale,
    backgroundColor: style.color.themeColor,
    color: style.color.white,
    textAlign: 'center'
  },
  tips: {
    width: 15 * scale,
    height: 15 * scale,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderRadius: 2 * scale,

  },
  tipsText: {
    fontSize: 10 * scale
  },
  changeText: {
    color: style.color.fontRed1,
    fontSize: 12 * scale,
    paddingLeft: 5 * scale
  },
  lockView: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    height: 12 * scale,
    width: 12 * scale,
    borderWidth: 1 * scale,
    borderColor: '#1660C8',
    marginLeft: 14 * scale,
    marginRight: 10 * scale,
  },
  lockImage: {
    width: 8 * scale,
    height: 6 * scale,
    tintColor: '#99C2EB',
  },
  listFlex: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    // alignItems: 'center'
  },
  bannerBox: {
    paddingLeft: 10 * scale,
    paddingTop: 5 * scale,
    paddingBottom: 10 * scale
  },
  bannerText: {
    color: '#F00707',
    fontSize: 12
  },
  applyStaffName: {
    fontSize: 10 * scale,
    color: '#7F7F7F',
    marginTop: 7 * scale
  },
  applyStaffNameNO: {
    fontSize: 10 * scale,
    color: '#7F7F7F',
    marginTop: 7 * scale,
    marginLeft: 15 * scale
  },
  lossDateText: {
    fontSize: 10 * scale,
    color: '#E02020',
    marginRight: 5 * scale
  },
  approveLogText: {
    fontSize: 10 * scale,
    color: style.color.themeColor,
  },
  auditingText: {
    alignSelf: 'center',
    color: '#F7B500',
    fontSize: 10 * scale,
    marginTop: 7 * scale
  },
})